package com.example.test_01.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.test_01.R;
import com.example.test_01.model.Food;
import com.example.test_01.service.FoodService;
import com.example.test_01.service.FoodServiceImpl;

import java.util.List;

public class FoodAdapter  extends RecyclerView.Adapter<FoodAdapter.ViewHolder>{

    private List<Food> list;
    private final FoodService service = new FoodServiceImpl();

    private void list(){
        list = service.list();
    }
    public FoodAdapter(){ list(); }
    public void reload(){
        list();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_type_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        holder.btn_food_type_item_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                Food food = list.get(position);

                service.DelFoodById(food.getId());
                list = service.list();
                notifyDataSetChanged();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Food food = list.get(position);
        holder.text_food_type_item_name.setText(food.getName() + "      " + food.getPrice() + '￥');
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView text_food_type_item_name;
        Button btn_food_type_item_del;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            text_food_type_item_name = itemView.findViewById(R.id.text_food_type_item_name);
            btn_food_type_item_del = itemView.findViewById(R.id.btn_food_type_item_del);
        }
    }
}
